package com.xxl.job.core.util;

import com.xxl.job.core.biz.model.DbInfo;
import com.xxl.job.core.constants.Constants;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/10/5.
 */
public class JdbcUtil {

    public static List<Map<String, Object>> getAllTables(DbInfo dbInfo) {
        if(dbInfo == null || Constants.DB_TYPE_MONGODB.equals(dbInfo.getDbType())) return null;

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(dbInfo.getDbDriver());
        dataSource.setUrl(dbInfo.getDbUrl());
        dataSource.setUsername(dbInfo.getDbUserName());
        dataSource.setPassword(dbInfo.getDbPassword());
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        List<Map<String, Object>> list;
        String dbName = dbInfo.getDbName();

        switch (dbInfo.getDbType()) { //根据数据库类型设置对应jdbc驱动
            case Constants.DB_TYPE_MYSQL: // mysql
                list = jdbcTemplate.queryForList("SELECT TABLE_NAME AS table_name,CASE WHEN IFNULL(TABLE_COMMENT,TABLE_NAME)='' THEN TABLE_NAME ELSE TABLE_COMMENT END AS table_comment FROM information_schema.`TABLES` WHERE TABLE_SCHEMA ='" + dbName + "'");
                break;
            case Constants.DB_TYPE_SQLSERVER:
                list = jdbcTemplate.queryForList("Select Name AS table_name,Name as table_comment FROM SysObjects Where XType='U'");
                break;
            case Constants.DB_TYPE_ORACLE:
                list = null;
                break;
            default:
                list = jdbcTemplate.queryForList("SELECT a.TABLE_NAME AS table_name,b.COMMENTS AS table_comment FROM user_tables a,user_tab_comments b WHERE a.TABLE_NAME=b.TABLE_NAME");
                break;
        }

        return list;
    }
}
